package com.reggie.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.reggie.common.R;
import com.reggie.entity.User;
import com.reggie.service.UserService;
import com.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息(User)表控制层
 *
 * @author makejava
 * @since 2022-09-07 17:10:34
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     *
     * @param user 前台登录用户实体
     * @return 成功与否
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取手机号
        String phone = user.getPhone();
        if (StrUtil.isNotEmpty(phone)) {
            // 获取随机生成的四位验证码
            String captcha = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("登录验证码：{}", captcha);
            // 调用阿里云短信服务
//            SMSUtils.sendMessage(
//                    "阿里云短信测试",
//                    "SMS_154950909",
//                    phone,
//                    "{\"code\":\"" + captcha + "\"}"
//            );
            // 保存验证码
            // session.setAttribute("phone", captcha);
            // 设置五分钟的验证码
            ValueOperations<String, String> stringOperations = redisTemplate.opsForValue();
            stringOperations.set(phone, captcha, 5, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 用户登录
     *
     * @param map     登陆参数
     * @param session session
     * @return 是否登录成功
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("接收参数：{}", map);
        // 获取手机号
        String phone = (String) map.get("phone");
        // 获取验证码
        String code = map.get("code").toString();
        // session比较验证码
        // String captcha = (String) session.getAttribute("phone");

        // 从redis中获取验证码
        ValueOperations<String, String> stringOperations = redisTemplate.opsForValue();
        String captcha = stringOperations.get(phone);
        if (StrUtil.isNotEmpty(captcha) && Objects.equals(captcha, code)) {
            // 新增 还是 登录
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class);
            queryWrapper.eq(User::getPhone, phone);
            int count = userService.count(queryWrapper);
            if (count == 0) {
                // 新增用户
                User newUser = new User();
                newUser.setPhone(phone);
                newUser.setName("用户" + IdWorker.getId());
                userService.save(newUser);
                session.setAttribute("user", newUser.getId());
                return R.success(newUser);
            }
            User loginUser = userService.getOne(queryWrapper);
            session.setAttribute("user", loginUser.getId());
            // 删除验证码缓存
            redisTemplate.delete(phone);
            return R.success(loginUser);
        }
        return R.error("登陆失败");
    }

    /**
     * 退出功能
     * ①在controller中创建对应的处理方法来接受前端的请求，请求方式为post；
     * ②清理session中的用户id
     * ③返回结果（前端页面会进行跳转到登录页面）
     *
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中的用户id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}

